import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd';
import {AccountService} from '../../account.service';
import {Observable} from "rxjs/Observable";

@Component({
  selector: 'app-top-up-money',
  templateUrl: './top-up-money.component.html',
  styleUrls: ['./top-up-money.component.scss'],
  providers: [AccountService]
})
export class TopUpMoneyComponent implements OnInit {
  validateForm: FormGroup;
  _isSpinning = false;
  page = 1;
  wxCode;

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
    if (this.validateForm.valid) {
      if (this.validateForm.controls['type'].value === 1) {
        this._isSpinning = true;
        this.accountService.wxpay({total_fee: this.validateForm.controls['total_fee'].value * 100}).subscribe(res => {
          console.log(res);
          this._isSpinning = false;
          if (res.code === 2000) {
            this.wxCode = res.data.code_url;
            this.page = 2;
            this.getWxPayStatus(res.data.out_trade_no);
          } else {
            this._message.error(res.message);
          }

        });
      } else {
        this._isSpinning = true;
        this.accountService.alipay({total_fee: this.validateForm.controls['total_fee'].value * 100, json: true}).subscribe(res => {
          this._isSpinning = false;
          if (res.code === 2000) {
            this.formPost(res.data.url, res.data.data);
          } else {
            this._message.error(res.message);
          }
        });
      }
    }
  }

  constructor(private fb: FormBuilder, private accountService: AccountService, private _message: NzMessageService, private router: Router) { }

  moneyValidator = (control: FormControl) => {
    return Observable.create((observer) => {
      setTimeout(() => {
        if (control.value < 0.01) {
          observer.next({ error: true, minNum: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 500);
    });
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      total_fee: [null, [Validators.required], [this.moneyValidator]],
      type: [null, [Validators.required]],
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  formPost(URL, PARAMS) {
    const temp = document.createElement('form');
    temp.action = URL;
    temp.method = 'post';
    temp.style.display = 'none';
    for (const x in PARAMS) {
      const opt = document.createElement('textarea');
      opt.name = x;
      opt.value = PARAMS[x];
      temp.appendChild(opt);
    }
    document.body.appendChild(temp);
    temp.submit();
    return temp;
  }

  getWxPayStatus(order_no) {
    setTimeout(() => {
      this.accountService.getWxPayStatus({order_no: order_no}).subscribe(res => {
        console.log(res);
        if (res.code === 2000) {
          if (res.data === true) {
            this.router.navigate(['/member/account/pay-success']);
          } else {
            this.getWxPayStatus(order_no);
          }
        } else {
          this._message.error(res.message);
        }
      });
    }, 5000);
  }
}
